console.log("Celeb Game Script Loaded");
// PRELOAD PHASE 1: Preload image function
// !! Requires image specifications in preload phase 2
$.preloadImages = function() {
	for (var i = 0; i < arguments.length; i++) {
		$("<img />").attr("src", arguments[i]);
	}
}

// PRELOAD PHASE 2: Image Selection
// !! Relative locations for image preloads
$.preloadImages(
	"/assets/images/desktop/celeb/modal.png", 
	"/assets/images/desktop/celeb/star-single.png", 
	"/assets/images/desktop/celeb/sprite1.png", 
	"/assets/images/desktop/celeb/sprite2.png", 
	"/assets/images/desktop/celeb/spider-sprite.png",

	"/assets/images/desktop/celeb/fly-sprite.png", 
	"/assets/images/desktop/celeb/star2.png", 
	"/assets/images/desktop/celeb/star3.png", 
	"/assets/images/desktop/celeb/star4.png", 
	"/assets/images/desktop/celeb/star5.png"
);

// Load CSS files
$('head').append('<link rel="stylesheet" href="/assets/css/celeb/animations-min.css" type="text/css" />');
$('body').append('<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>');
// $('head').append('<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" type="text/css" />');
$('body').append('<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>');
$('body').append('<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>');

// Persist Variables
var gameOn = localStorage.getItem('Game');

// Load game controls and modal 
	$.get("/assets/html/celeb/modals/dialog.html", function(data){
    	$('#wrapper').append(data);
       
		// Keep interface alive if game is active
		if (gameOn == 'Active') {
			
			// Show all game controls
			$('.gamePersist').show();
         
			// Find out how many stars have been found so far
			var starsFound = localStorage.getItem('IAC_S');
		 
			// Remove collected class and show all stars	 
			$('.star').removeClass('collected').show();

			// Add collected class to applicable stars
			$('.star1').addClass('collected');  
			$('.star' + starsFound).addClass('collected');  
		 
       };
	});


// BUILD GAME FOUNDATIONS
// Required content holders for game 
//$.ajax({
//    url: "/assets/html/celeb/modals/dialog.html",
//    success: function (data) { $('#wrapper').append(data); },
//    dataType: 'html'
//});

// GAME FUNCTION: Introduction Dialog
// Builds dialog and modals (additional modals found in /modals/ folder)
function gameIntro() {

	// Developer log
	console.log("GAME: User Initiated Game");

	// Open welcome/intro dialog
	$( "#dialog-confirm" ).dialog({
		resizable: false,
		height:360,
		width:650,
		modal: true,
		show: 'fade',
    dialogClass: 'imaceleb',
		hide: 'fade',
		open: function( event, ui ) { 
			$('.entry-choice').fadeIn(); 
			$('.ui-dialog-buttonset').show(); 
			$(this).closest(".ui-dialog").find(".ui-button:contains(Start)").css("width","160px");
			$(this).closest(".ui-dialog").find(".ui-button:contains(No)").addClass("grey-btn");
		},
		buttons: {
			// If user starts trial
			"Start Trial": function() {
        
        $('.entry-choice').append('<audio class="music" autoplay="true" src="/assets/audio/celeb-intro.mp3"></audio>');
				
				// Developer logs
				console.log("GAME: User Began Trial");
				console.log("GAME: Building Heads Up Display");

				// Set local storage of game to active and stars to 0
				localStorage.setItem('Game','Active');
		var starsFound = localStorage.setItem('IAC_S','0');
				
				// Hide first modal contents div
				$('.entry-choice').hide();
				
				// Show loading screen (hide buttons, move leaves)
				$('.entry-yes').fadeIn();
        $('body').css('background-image', 'url("/assets/images/desktop/celeb/bg2.jpg")');
        $('body').css('background-position','top center');
        $('body').css('background-repeat','no-repeat');
        $('body').css('background-color','#ffffff');
				$('.ui-dialog-buttonset').fadeOut();
				$( '.dialog-leaves-top').css('background-position','-6px 50px');
				$( '.dialog-leaves-bottom').css('background-position','-690px -5px');	

				// After 1 second bring in all the game controls
				setTimeout(function(){
					$('.celeb-bg').fadeIn(750);
					$('#gameControls').show().addClass("animatedUp bounceInUp");
					$('#stars').delay(750).show(0).addClass("animatedIn bounceInUp");					
				}, 1000);

				// Show each star pop in one by one
				setTimeout(function(){
					$(".star").each(function(s,el) {
						var $this = $(this);
						setTimeout(function() {
								$this.show().addClass('animatedIn bounceIn');
							}, s*200); // milliseconds
					});		
				}, 2000);

				// Show game prompt area
				setTimeout(function(){
					$( '.gamePrompt').show().addClass("animatedIn bounceInUp");
				}, 3000);				

				// Show game exit sign
				setTimeout(function(){
					$( '.gameExit').show().addClass("exitAnim exitAnimation");
				}, 4000);	

				// When loading is complete
				setTimeout(function(){

					// Fade out loading text
					$('.entry-yes p').fadeOut();

					// Move leaves out of the way again
					$('.dialog-leaves-top').css('background-position','-6px 0px');					
					$('.dialog-leaves-bottom').css('background-position','-690px 40px');
						
					// Remove all classes from individual stars
					$(".star").each(function(s,el) {
						var $this = $(this);
						setTimeout(function() {
								$this.show().removeClass('animatedIn bounceIn');
							}, s*20); // milliseconds
					});	

					// Developer log
					console.log("GAME: Build Complete");

				}, 5000);								
				 
				// All elements are loaded (6 seconds) 
				setTimeout(function(){

					// Developer log
					console.log("GAME: Load Modal Screen Stage 2");

					// Reset all stars invidiually to uncollected status
					$(".star").each(function(i,el) {
						var $this = $(this);
						setTimeout(function() {
								$this.removeClass('collected');
							}, i*50); // milliseconds
					});			

					// Hide modal content and load second screen		
					$('.entry-yes').hide().load("/assets/html/celeb/modals/screen2.html");

					// Fade in modal content
					$('.entry-yes').fadeIn(650);

				 }, 6000);
			},

			// If user chooses NO to game
			"No thanks!": function() {

				// Set local storage to game of inactive
				localStorage.setItem('Game','Inactive');

				// Close game dialog
				$(this).dialog( "close" );
			}
		}
	});

	// Close Dialog Icon
	$('.dialog-close').click(function() {
		// On click, close dialog
		$('.celeb-dialog').dialog( "close" );
	});

	// Get Me Out of Here Click
	$('.gameExit').click(function() {

		// Developer Log
		console.log("GAME: User has clicked GET ME OUT OF HERE");

		// Run game exit
		exitGame();
	});
};


// GAME FUNCTION: START
function beginGame() {

	// Developer logs
	console.log("GAME: Load complete!");
	console.log("GAME: Wait 2 seconds before initiating free first star");

	// Remove animation classes and apply hover function to exit sign
	$('.gameExit').removeClass('exitAnim exitAnimation').hover(
		function() {
			$( this ).addClass('wobbleAnim wobble')
		}, function() {
			$( this ).removeClass('wobbleAnim wobble');
		}
	);

	// Free first star after 1 seconds of game load
	setTimeout(function(){

		// Set class and animate star1
		$('.star1').addClass('collected animatedTada tada');
		
		// Update game prompt text
		$('.gamePromptText').html("<span class=\"promptIcon thestar\"></span><p>Here's your first star to get you started! Remember there’s no time limit!</p>").fadeIn(500);	
		
		// Developer log
		console.log("GAME: [STAR] Star 1 collected");
	
	},1000);
}

// GAME FUNCTION: COMPLETE
// If all 5 stars collected, game status is complete
function completeGame(){ 
	
	// Developer logs
	console.log("GAME: User has completed game");

	// Remove all classes from the stars so we can reanimate
	$('.star').removeClass("animatedTada tada");

	// Add animation to each star sequentially
	$(".star").each(function(s,el) {
		var $this = $(this);
		setTimeout(function() {
				$this.addClass('animatedTada tada');
			}, s*250); // milliseconds

		// Remove animation again
		setTimeout(function() {
		$('.star').removeClass("animatedTada tada");
		},1900);
	});	

	// Animate all stars at the same time
	setTimeout(function() {
		$('.star').addClass("animatedTada tada");
	},2000);

};


// GAME PERSIST
// Keep game running and visible
function continueGame() {
	
	// Keep all game controls on screen
	$('.gamePersist').show();
  $('#wrapper').find('.gamePersist').css('display','block');
  $('body').css('background-colour','red');
  console.log('Continue game function has run')
	// Keep only collected stars showing
 };


// GAME FUNCTION: EXIT
// If user exits, remove elements and clear storage variable
// !! Requires browser refresh to re-enter the game
function exitGame() {

	// Developer logs
	console.log("GAME: User has requested to end game");

	// Open welcome/intro dialog
	$( "#dialog-confirm" ).dialog({
		resizable: false,
		height:360,
		width:650,
		modal: true,
		show: 'fade',
		hide: 'fade',
		open: function( event, ui ) { 
			$('.entry-choice').fadeIn(); 
			$('.ui-dialog-buttonset').show(); 
			$(this).closest(".ui-dialog").find(".ui-button:contains(Keep)").css("width","160px");
			$(this).closest(".ui-dialog").find(".ui-button:contains(Leave)").addClass("red-btn");
		},
		buttons: {
			// If user starts trial
			"Keep Playing": function() {

				// Close exit dialog
				$(this).dialog( "close" );

				// Developer logs
				console.log("GAME: User chose to keep playing");
			},

			// If user chooses NO to game
			"Leave Trial": function() {

				// Set local storage to game of inactive
				localStorage.setItem('Game','Inactive');

				// Close Modal
				$('.celeb-dialog').dialog( "close" );

				// Define elements to remove
				var elements = ['.gameExit', '.gamePrompt', '#stars', '#gameControls', '.celeb-bg'];

				// Remove each element with a 250ms delay
				$.each(elements, function(index, item) {
					var timeout = (index == 0 ? 1 : index) * 250;
					
					// Only animate the removal of none background elements 
					if (item != '.celeb-bg') {
						setTimeout(function() { 
							$(item).addClass("hideanimation hide");
						}, timeout);
					} else {  
						// Fade the background out
						$(item).fadeOut();
					}
				});

				// Developer Log
				console.log("GAME: User has quit")

			}
		}
	});

	// Set content of modal for quit game message
	$('.entry-choice').html('<span class=\"title icelandtrialwelcome\"></span><h2>YOUR SHOPPING BASKET WON’T BE AFFECTED, BUT YOUR TRIAL PROGESS SO FAR WILL BE LOST?</h2>');
	$('.entry-yes').hide();
};

// GAME FUNCTION: SHOW STARS
// Individual functions for star display
function showStar(star) {

		if (isNaN(star)) return false;

		var class_name = '.celeb-star' + star;
		var file_name = '/assets/html/celeb/stars/star' + star + '.html';
		var div_name = class_name.substr(1);

        // Check if star exists already
        if($(class_name).length == 0) {

          if (star == 2 || star == 4) {
          // Insert star4 div container
                $('#fullWidthHeader').append("<div class=\""+div_name+"\"></div>");
          } else {
                // Insert star4 div container
                $('#wrapper').append("<div class=\""+div_name+"\"></div>");
          };
                // Load external content into star4 container
                $(class_name).load(file_name);

                // Developer Log
                console.log("GAME: Star " + star + " is now visible");

                // Load additional script if star 5
                if (star == 5) {
                	$.getScript("/assets/js/celeb/star5.js");

                	// Developer Log
                	console.log("GAME: Additional javascript loaded for star "+star);
                }
        };
};


// Bug Removal Function
function removeBugs() {
	
	// Find each bug on page
	$('.bug').each(function( index ) {
		// Remove all bugs
		$(this).remove();

		// Developer Log
		console.log("GAME: All Bugs Removed");
	});
};


// DEVELOPER TOOLS
// !! Remove before production
$('body').keyup(function(e){

	// On enter key, load game
	if(e.keyCode == 83){
		gameIntro();
	}

	// On END key, exist game
	if(e.keyCode == 81){
		exitGame();
	}

	// On '2' key, show star 2
	if(e.keyCode == 50){
		showStar(2);
	}

	// On '3' key, show star 3
	if(e.keyCode == 51){
		showStar(3);
	}

	// On '4' key, show star 4
	if(e.keyCode == 52){
		showStar(4);
	}

	// On '5' key, show star 5
	if(e.keyCode == 53){
		showStar(5);
	}
});